package top.z.work.framework.web.util;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.z.work.framework.common.pojo.R;

/**
 * WEB包的工具类
 */
public class WebFrameworkUtil {

    private static final String REQUEST_ATTRIBUTE_COMMON_RESULT = "common_result";

    public WebFrameworkUtil() {
    }

    public static void setResult(ServletRequest request, R<?> result) {
        request.setAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT, result);
    }

    public static R<?> getResult(ServletRequest request) {
        return (R<?>) request.getAttribute(REQUEST_ATTRIBUTE_COMMON_RESULT);
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (!(requestAttributes instanceof ServletRequestAttributes servletRequestAttributes)) {
            return null;
        }
        return servletRequestAttributes.getRequest();
    }

}
